<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加商品</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        .image-upload-area {
            border: 2px dashed #d1d5db;
            transition: all 0.3s ease;
        }
        .image-upload-area:hover {
            border-color: #6366f1;
            background-color: #fafbff;
        }
        .image-upload-area.dragover {
            border-color: #6366f1;
            background-color: #f0f4ff;
        }
        .spec-input-group {
            border: 1px solid #e5e7eb;
            border-radius: 8px;
        }
    </style>
</head>
<body class="bg-gray-100">
    <div class="mx-auto max-w-[393px] h-[852px] bg-white relative overflow-hidden rounded-[40px] shadow-2xl">
        <!-- Status Bar -->
        <div class="bg-white px-6 pt-3 pb-2">
            <div class="flex justify-between items-center text-xs">
                <span class="font-semibold">9:41</span>
                <div class="flex space-x-1">
                    <i class="fas fa-signal"></i>
                    <i class="fas fa-wifi"></i>
                    <i class="fas fa-battery-full"></i>
                </div>
            </div>
        </div>

        <!-- Header -->
        <div class="bg-gradient-to-r from-indigo-600 to-purple-600 px-4 py-3">
            <div class="flex items-center justify-between text-white">
                <button onclick="goBack()" class="text-white">
                    <i class="fas fa-arrow-left text-lg"></i>
                </button>
                <h1 class="text-lg font-semibold">添加商品</h1>
                <button onclick="saveDraft()" class="text-white text-sm">
                    暂存
                </button>
            </div>
        </div>

        <!-- Form Content -->
        <div class="h-[calc(852px-120px)] overflow-y-auto pb-20">
            <form id="productForm" class="p-4 space-y-6">
                <!-- Product Images -->
                <div class="bg-white rounded-lg p-4 border border-gray-200">
                    <div class="flex items-center justify-between mb-3">
                        <h3 class="font-semibold">商品图片</h3>
                        <span class="text-xs text-gray-500">最多9张</span>
                    </div>
                    
                    <div class="grid grid-cols-3 gap-2 mb-3" id="image-preview">
                        <!-- Uploaded images will appear here -->
                    </div>
                    
                    <div class="image-upload-area rounded-lg p-6 text-center cursor-pointer" onclick="triggerImageUpload()">
                        <i class="fas fa-camera text-2xl text-gray-400 mb-2"></i>
                        <p class="text-sm text-gray-500">点击添加商品图片</p>
                        <p class="text-xs text-gray-400 mt-1">建议尺寸：800x800像素</p>
                    </div>
                    <input type="file" id="imageInput" multiple accept="image/*" class="hidden" onchange="handleImageUpload(event)">
                </div>

                <!-- Basic Information -->
                <div class="bg-white rounded-lg p-4 border border-gray-200">
                    <h3 class="font-semibold mb-3">基本信息</h3>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">商品名称 *</label>
                            <input type="text" id="productName" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="请输入商品名称" maxlength="60">
                            <p class="text-xs text-gray-500 mt-1">0/60字符</p>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">商品分类 *</label>
                            <select id="productCategory" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent">
                                <option value="">请选择分类</option>
                                <option value="electronics">数码电子</option>
                                <option value="clothing">服装配饰</option>
                                <option value="home">家居用品</option>
                                <option value="beauty">美妆个护</option>
                                <option value="sports">运动户外</option>
                                <option value="books">图书文具</option>
                                <option value="food">食品保健</option>
                            </select>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">品牌</label>
                            <input type="text" id="productBrand" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="请输入品牌名称">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">商品描述</label>
                            <textarea id="productDescription" rows="4" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent resize-none" placeholder="详细描述您的商品特色和优势" maxlength="500"></textarea>
                            <p class="text-xs text-gray-500 mt-1">0/500字符</p>
                        </div>
                    </div>
                </div>

                <!-- Pricing -->
                <div class="bg-white rounded-lg p-4 border border-gray-200">
                    <h3 class="font-semibold mb-3">价格设置</h3>
                    
                    <div class="space-y-4">
                        <div class="grid grid-cols-2 gap-3">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">销售价 *</label>
                                <div class="relative">
                                    <span class="absolute left-3 top-2 text-gray-500">¥</span>
                                    <input type="number" id="salePrice" class="w-full pl-8 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="0.00" step="0.01" min="0">
                                </div>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">原价</label>
                                <div class="relative">
                                    <span class="absolute left-3 top-2 text-gray-500">¥</span>
                                    <input type="number" id="originalPrice" class="w-full pl-8 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="0.00" step="0.01" min="0">
                                </div>
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">成本价</label>
                            <div class="relative">
                                <span class="absolute left-3 top-2 text-gray-500">¥</span>
                                <input type="number" id="costPrice" class="w-full pl-8 pr-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="0.00" step="0.01" min="0">
                            </div>
                            <p class="text-xs text-gray-500 mt-1">用于利润计算，不会显示给买家</p>
                        </div>
                    </div>
                </div>

                <!-- Inventory -->
                <div class="bg-white rounded-lg p-4 border border-gray-200">
                    <h3 class="font-semibold mb-3">库存管理</h3>
                    
                    <div class="space-y-4">
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">库存数量 *</label>
                            <input type="number" id="stockQuantity" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="请输入库存数量" min="0">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">库存预警值</label>
                            <input type="number" id="stockAlert" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="库存低于此数量时提醒" min="0">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">商品编码/SKU</label>
                            <input type="text" id="productSku" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="自动生成或手动输入">
                            <button type="button" onclick="generateSKU()" class="text-xs text-indigo-600 hover:text-indigo-800 mt-1">自动生成SKU</button>
                        </div>
                    </div>
                </div>

                <!-- Product Specifications -->
                <div class="bg-white rounded-lg p-4 border border-gray-200">
                    <div class="flex items-center justify-between mb-3">
                        <h3 class="font-semibold">商品规格</h3>
                        <button type="button" onclick="addSpecification()" class="text-sm text-indigo-600 hover:text-indigo-800">
                            <i class="fas fa-plus mr-1"></i>添加规格
                        </button>
                    </div>
                    
                    <div id="specifications" class="space-y-3">
                        <!-- Specifications will be added here -->
                    </div>
                </div>

                <!-- Shipping -->
                <div class="bg-white rounded-lg p-4 border border-gray-200">
                    <h3 class="font-semibold mb-3">物流信息</h3>
                    
                    <div class="space-y-4">
                        <div class="grid grid-cols-3 gap-3">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">重量(kg)</label>
                                <input type="number" id="weight" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="0.0" step="0.1" min="0">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">长(cm)</label>
                                <input type="number" id="length" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="0" min="0">
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-1">宽(cm)</label>
                                <input type="number" id="width" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="0" min="0">
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">高(cm)</label>
                            <input type="number" id="height" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="0" min="0">
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">运费模板</label>
                            <select id="shippingTemplate" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent">
                                <option value="">使用默认运费</option>
                                <option value="free">包邮</option>
                                <option value="template1">数码产品运费模板</option>
                                <option value="template2">服装配件运费模板</option>
                                <option value="custom">自定义运费</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Sales Settings -->
                <div class="bg-white rounded-lg p-4 border border-gray-200">
                    <h3 class="font-semibold mb-3">销售设置</h3>
                    
                    <div class="space-y-4">
                        <div class="flex items-center justify-between">
                            <span class="text-sm font-medium text-gray-700">立即上架</span>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" id="autoPublish" class="sr-only peer" checked>
                                <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
                            </label>
                        </div>
                        
                        <div class="flex items-center justify-between">
                            <span class="text-sm font-medium text-gray-700">允许退换货</span>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" id="allowReturn" class="sr-only peer" checked>
                                <div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-indigo-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-indigo-600"></div>
                            </label>
                        </div>
                        
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">限购数量</label>
                            <input type="number" id="purchaseLimit" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent" placeholder="不限制" min="1">
                            <p class="text-xs text-gray-500 mt-1">每个用户最多购买数量，留空表示不限制</p>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <!-- Bottom Action Buttons -->
        <div class="absolute bottom-0 left-0 right-0 bg-white border-t border-gray-200 p-4">
            <div class="flex gap-3">
                <button onclick="saveDraft()" class="flex-1 bg-gray-100 text-gray-700 py-3 rounded-lg font-medium hover:bg-gray-200 transition-colors">
                    保存草稿
                </button>
                <button onclick="publishProduct()" class="flex-1 bg-gradient-to-r from-indigo-600 to-purple-600 text-white py-3 rounded-lg font-medium hover:opacity-90 transition-opacity">
                    发布商品
                </button>
            </div>
        </div>
    </div>

    <script>
        let uploadedImages = [];
        let specificationCount = 0;

        // Go back to products page
        function goBack() {
            if (hasUnsavedChanges()) {
                if (confirm('您有未保存的修改，确定要离开吗？')) {
                    window.location.href = 'b2b-products.html';
                }
            } else {
                window.location.href = 'b2b-products.html';
            }
        }

        // Check for unsaved changes
        function hasUnsavedChanges() {
            const productName = document.getElementById('productName').value;
            const productCategory = document.getElementById('productCategory').value;
            const salePrice = document.getElementById('salePrice').value;
            
            return productName || productCategory || salePrice || uploadedImages.length > 0;
        }

        // Image upload functionality
        function triggerImageUpload() {
            document.getElementById('imageInput').click();
        }

        function handleImageUpload(event) {
            const files = Array.from(event.target.files);
            
            files.forEach(file => {
                if (uploadedImages.length >= 9) {
                    alert('最多只能上传9张图片');
                    return;
                }
                
                if (file.type.startsWith('image/')) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        uploadedImages.push({
                            file: file,
                            url: e.target.result,
                            id: Date.now() + Math.random()
                        });
                        updateImagePreview();
                    };
                    reader.readAsDataURL(file);
                }
            });
        }

        function updateImagePreview() {
            const preview = document.getElementById('image-preview');
            preview.innerHTML = '';
            
            uploadedImages.forEach((image, index) => {
                const imageDiv = document.createElement('div');
                imageDiv.className = 'relative aspect-square bg-gray-100 rounded-lg overflow-hidden';
                imageDiv.innerHTML = `
                    <img src="${image.url}" alt="商品图片" class="w-full h-full object-cover">
                    <button onclick="removeImage(${image.id})" class="absolute top-1 right-1 bg-red-500 text-white rounded-full w-5 h-5 flex items-center justify-center text-xs hover:bg-red-600">
                        <i class="fas fa-times"></i>
                    </button>
                    ${index === 0 ? '<span class="absolute bottom-1 left-1 bg-indigo-600 text-white text-xs px-1 rounded">主图</span>' : ''}
                `;
                preview.appendChild(imageDiv);
            });
        }

        function removeImage(imageId) {
            uploadedImages = uploadedImages.filter(img => img.id !== imageId);
            updateImagePreview();
        }

        // Generate SKU
        function generateSKU() {
            const category = document.getElementById('productCategory').value;
            const timestamp = Date.now().toString().slice(-6);
            const random = Math.random().toString(36).substr(2, 4).toUpperCase();
            
            const categoryCode = {
                'electronics': 'ELE',
                'clothing': 'CLO',
                'home': 'HOM',
                'beauty': 'BEA',
                'sports': 'SPO',
                'books': 'BOO',
                'food': 'FOO'
            };
            
            const prefix = categoryCode[category] || 'PRO';
            const sku = `${prefix}${timestamp}${random}`;
            
            document.getElementById('productSku').value = sku;
        }

        // Add specification
        function addSpecification() {
            specificationCount++;
            const specificationsDiv = document.getElementById('specifications');
            
            const specDiv = document.createElement('div');
            specDiv.className = 'spec-input-group p-3';
            specDiv.id = `spec-${specificationCount}`;
            specDiv.innerHTML = `
                <div class="flex items-center justify-between mb-2">
                    <span class="text-sm font-medium">规格 ${specificationCount}</span>
                    <button type="button" onclick="removeSpecification(${specificationCount})" class="text-red-500 text-sm">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
                <div class="grid grid-cols-2 gap-2">
                    <input type="text" placeholder="规格名称（如：颜色）" class="px-2 py-1 border border-gray-300 rounded text-sm">
                    <input type="text" placeholder="规格值（如：红色）" class="px-2 py-1 border border-gray-300 rounded text-sm">
                </div>
            `;
            
            specificationsDiv.appendChild(specDiv);
        }

        function removeSpecification(id) {
            const specDiv = document.getElementById(`spec-${id}`);
            if (specDiv) {
                specDiv.remove();
            }
        }

        // Save draft
        function saveDraft() {
            const formData = collectFormData();
            formData.status = 'draft';
            
            // Simulate saving to localStorage
            const drafts = JSON.parse(localStorage.getItem('productDrafts') || '[]');
            drafts.push({
                ...formData,
                id: Date.now(),
                savedAt: new Date().toISOString()
            });
            localStorage.setItem('productDrafts', JSON.stringify(drafts));
            
            alert('草稿已保存！\n\n您可以稍后在草稿箱中继续编辑。');
        }

        // Publish product
        function publishProduct() {
            if (!validateForm()) {
                return;
            }
            
            if (confirm('确定要发布这个商品吗？\n\n发布后商品将立即在您的店铺中展示。')) {
                const formData = collectFormData();
                formData.status = 'published';
                formData.publishedAt = new Date().toISOString();
                
                // Simulate API call
                showPublishProgress();
            }
        }

        // Validate form
        function validateForm() {
            const productName = document.getElementById('productName').value.trim();
            const productCategory = document.getElementById('productCategory').value;
            const salePrice = document.getElementById('salePrice').value;
            const stockQuantity = document.getElementById('stockQuantity').value;
            
            if (!productName) {
                alert('请输入商品名称');
                document.getElementById('productName').focus();
                return false;
            }
            
            if (!productCategory) {
                alert('请选择商品分类');
                document.getElementById('productCategory').focus();
                return false;
            }
            
            if (!salePrice || parseFloat(salePrice) <= 0) {
                alert('请输入有效的销售价格');
                document.getElementById('salePrice').focus();
                return false;
            }
            
            if (!stockQuantity || parseInt(stockQuantity) < 0) {
                alert('请输入有效的库存数量');
                document.getElementById('stockQuantity').focus();
                return false;
            }
            
            if (uploadedImages.length === 0) {
                alert('请至少上传一张商品图片');
                return false;
            }
            
            return true;
        }

        // Collect form data
        function collectFormData() {
            return {
                productName: document.getElementById('productName').value.trim(),
                productCategory: document.getElementById('productCategory').value,
                productBrand: document.getElementById('productBrand').value.trim(),
                productDescription: document.getElementById('productDescription').value.trim(),
                salePrice: parseFloat(document.getElementById('salePrice').value) || 0,
                originalPrice: parseFloat(document.getElementById('originalPrice').value) || 0,
                costPrice: parseFloat(document.getElementById('costPrice').value) || 0,
                stockQuantity: parseInt(document.getElementById('stockQuantity').value) || 0,
                stockAlert: parseInt(document.getElementById('stockAlert').value) || 0,
                productSku: document.getElementById('productSku').value.trim(),
                weight: parseFloat(document.getElementById('weight').value) || 0,
                dimensions: {
                    length: parseFloat(document.getElementById('length').value) || 0,
                    width: parseFloat(document.getElementById('width').value) || 0,
                    height: parseFloat(document.getElementById('height').value) || 0
                },
                shippingTemplate: document.getElementById('shippingTemplate').value,
                autoPublish: document.getElementById('autoPublish').checked,
                allowReturn: document.getElementById('allowReturn').checked,
                purchaseLimit: parseInt(document.getElementById('purchaseLimit').value) || 0,
                images: uploadedImages,
                specifications: getSpecifications()
            };
        }

        // Get specifications
        function getSpecifications() {
            const specs = [];
            const specDivs = document.querySelectorAll('[id^="spec-"]');
            
            specDivs.forEach(div => {
                const inputs = div.querySelectorAll('input');
                if (inputs.length === 2 && inputs[0].value.trim() && inputs[1].value.trim()) {
                    specs.push({
                        name: inputs[0].value.trim(),
                        value: inputs[1].value.trim()
                    });
                }
            });
            
            return specs;
        }

        // Show publish progress
        function showPublishProgress() {
            const progressHTML = `
                <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div class="bg-white rounded-lg p-6 max-w-sm mx-4">
                        <div class="text-center">
                            <i class="fas fa-spinner fa-spin text-3xl text-indigo-600 mb-4"></i>
                            <p class="text-lg font-semibold mb-2">发布中...</p>
                            <p class="text-sm text-gray-600">正在上传商品信息和图片</p>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', progressHTML);
            
            // Simulate publish process
            setTimeout(() => {
                document.querySelector('.fixed.inset-0').remove();
                alert('商品发布成功！\n\n您的商品已成功发布到店铺中，买家现在可以看到并购买您的商品了。');
                window.location.href = 'b2b-products.html';
            }, 2000);
        }

        // Character counter for text inputs
        function setupCharacterCounters() {
            const productName = document.getElementById('productName');
            const productDescription = document.getElementById('productDescription');
            
            productName.addEventListener('input', function() {
                const counter = productName.parentNode.querySelector('.text-xs');
                counter.textContent = `${this.value.length}/60字符`;
            });
            
            productDescription.addEventListener('input', function() {
                const counter = productDescription.parentNode.querySelector('.text-xs');
                counter.textContent = `${this.value.length}/500字符`;
            });
        }

        // Initialize page
        document.addEventListener('DOMContentLoaded', function() {
            setupCharacterCounters();
            
            // Auto-generate SKU when category changes
            document.getElementById('productCategory').addEventListener('change', function() {
                if (this.value && !document.getElementById('productSku').value) {
                    generateSKU();
                }
            });
            
            // Prevent form submission on enter
            document.getElementById('productForm').addEventListener('submit', function(e) {
                e.preventDefault();
            });
            
            // Add a default specification for demonstration
            addSpecification();
        });
    </script>
</body>
</html>